package box.tuson.com.tusonbox;

import android.content.*;
import android.content.pm.*;
import android.os.*;
import android.support.design.widget.*;
import android.support.v4.view.*;
import android.support.v4.widget.*;
import android.support.v7.app.*;
import android.support.v7.widget.*;
import android.view.*;
import android.widget.*;
import box.tuson.com.tusonbox.bmob.*;
import cn.bmob.v3.*;
import cn.bmob.v3.listener.*;
import java.util.*;
import android.content.SharedPreferences.Editor;
import box.tuson.com.tusonbox.widgets.ActionSheetDialog.SheetItemColor;
import box.tuson.com.tusonbox.widgets.ActionSheetDialog.SheetItemColor;
import box.tuson.com.tusonbox.widgets.ActionSheetDialog.OnSheetItemClickListener;

import android.support.v7.widget.Toolbar;
import box.tuson.com.tusonbox.widgets.*;
import android.net.*;
import cn.pedant.SweetAlert.*;

public class Main extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
	int button= 0;
	
	private TextView jd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		Bmob.initialize(this, "9a567bc11b8632383f69cd4c165c5a2a");
		
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "更多功能即将添加...您若有什么建议可以点击右上角把您的建议发给给我们", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
   
		//读取update表中数据
		BmobQuery<update> Appupdate=new BmobQuery<update>();
		Appupdate.setLimit(50);
		Appupdate.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);
		Appupdate.findObjects(Main.this, new FindListener<update>(){

				//获取版本号
				private String getAppVersion()
				{
					try
					{
						PackageManager pack = getPackageManager() ;
						PackageInfo info = pack.getPackageInfo(getPackageName(), 0) ;
						return info.versionName ;
					}
					catch (PackageManager.NameNotFoundException e)
					{
						e.printStackTrace();
					}

					return null;
				}
//结束
				
				@Override
				public void onSuccess(List<update> p1)
				{

					for (update ud:p1)
					{  
						//获取更新标题
						String updateTitle=ud.gettitle();
						//获取更新日志
						String updateMessage=ud.getmessage();
						//获取下载地址
						final String updateDownload = ud.getDownload();
						//更新功能这里我们就用if else做判断。
						String AppVersion = getAppVersion();
						String version=(AppVersion);//AppVersion值转string类型等于获取的版本号
						if (version.equals(ud.getversion()))
						{
							toast("发现新版本啦");
						 new SweetAlertDialog(Main.this)
								.setTitleText(updateTitle)
								.setContentText(updateMessage)
								.setConfirmText("下载")
								.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {

									@Override
									public void onClick(SweetAlertDialog sweetAlertDialog)
									{
										// TODO: Implement this method
										if (button <= 1)
										{
											final AlertDialog dia = new AlertDialog.Builder(Main.this).create();  
											dia.show();  
											dia.setCancelable(false);
											Window window = dia.getWindow();  
											window.setContentView(R.layout.xiazai); 
											WindowManager m = Main.this.getWindowManager();
											Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
											WindowManager.LayoutParams params = window.getAttributes();  
											params.width = (int) (d.getWidth() * 0.8);
											window.setAttributes(params);//此句代码一定要放在show()后面，否则不起作用  
											dia.setCanceledOnTouchOutside(false); 
											jd = (TextView)window.findViewById(R.id.jd);
											Download down=new Download();
											down.setondown(new Download.ondown()
												{
													@Override
													public void downing(int len, int oklen)
													{
														jd.setText("下载进度：" + (int)(((double)oklen / (double)len) * 100) + "%");
													}
													@Override
													public void downok(String ruest)
													{
														dia.dismiss();
														AutoInstall.setUrl(Environment.getExternalStorageDirectory()
																		   + "/Download/TuSonBox.apk");
														AutoInstall.install(Main.this);
													}
												});

											down.dowmFile(updateDownload, "/mnt/sdcard/Download/" + "TuSonBox.apk");


										}
									
						      }

								})
								.show();	
						}
						/*不显示出来
					else
					{
						toast("已经是最新版本啦");
					}
					*/
					}}

				private void toast(String message)
				{
					Toast.makeText(Main.this, message.trim(), Toast.LENGTH_SHORT).show();
				}


				@Override
				public void onError(int p1, String p2)
				{
					Toast.makeText(Main.this, "检测失败，请检查网络连接哦", Toast.LENGTH_LONG).show();
				}});

		
		SharedPreferences share1 = this.getSharedPreferences("share", MODE_PRIVATE);
		boolean isFirstRun1=share1.getBoolean("wxts", true);
		final Editor editor1=share1.edit();

		if (isFirstRun1)
		{
			new SweetAlertDialog(this)
			    .setTitleText("温馨提示")
				.setContentText("欢迎使用TuSon Box!当您使用TuSon Box部分功能会需要和消耗您的网络，但是只是很少的，若您使用的过程中有不会使用和使用过程中不满意的可以联系我们TuSon Box，QQ群号码:5803179，微信公众平台:TuSon另外祝您使用愉快～")
				.setConfirmText("Ok")
				.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {

					@Override
					public void onClick(SweetAlertDialog sweetAlertDialog)
					{
						// TODO: Implement this method
						editor1.putBoolean("wxts", false);

						editor1.commit();	
						sweetAlertDialog.cancel();
					}	
					
				})
				.show();
		}	
}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{

			ActionSheetDialog sheetdialog=  new ActionSheetDialog(Main.this);
			sheetdialog.builder();
			sheetdialog.setTitle("是否退出");
			//  sheetdialog.setCancelable(false);
			//  sheetdialog.setCanceledOnTouchOutside(false);
			sheetdialog.addSheetItem("最小化", SheetItemColor.Blue, new OnSheetItemClickListener() {
					@Override
					public void onClick(int which)
					{
						Intent intent = new Intent();
						intent.setAction("android.intent.action.MAIN");
						intent.addCategory("android.intent.category.HOME");
						Main.this.startActivity(intent);
					}
				});
			sheetdialog.addSheetItem("退出", SheetItemColor.Blue, new OnSheetItemClickListener(){

					@Override
					public void onClick(int which)
					{
						Main.this.finish();
					}
				});
			sheetdialog.show();

		}
		return true;
	}

	
		
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent textIntent = new Intent(Intent.ACTION_SEND);
			textIntent.setType("text/plain");
			textIntent.putExtra(Intent.EXTRA_TEXT, "TuSon Box是一款实用简单且又免费无广告绿色的一个工具箱盒子，功能有QQ加速，拉QQ圈圈，QQ音乐加速，特殊文字，网页源码查看等等功能，欢迎大家来使用，下载地址:https://www.pgyer.com/TuSonBox");
			startActivity(Intent.createChooser(textIntent, "分享TuSon Box"));
           return true;
        } else if(id == R.id.action_fk){
			startActivity(new Intent(this, jyyfk.class));
		}

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_qqqq) {
			startActivity(new Intent(this, qqlqq.class));//系统自带
            // Handle the camera action
        } else if (id == R.id.nav_qqcheg) {
			startActivity(new Intent(this, qqcheg.class));
        } else if (id == R.id.nav_qqkjwb) {
			startActivity(new Intent(this, qqkjwb.class));
        } else if (id == R.id.nav_qqqzlt) {
			startActivity(new Intent(this, qqqzlt.class));
        } else if (id == R.id.nav_qqdjjs) {
			startActivity(new Intent(this, qqjs.class));
        } else if (id == R.id.nav_tswz) {
			startActivity(new Intent(this, tswz.class));
        } else if (id == R.id.nav_dlj){
			startActivity(new Intent(this, dlj.class));
		} else if (id == R.id.nav_qqyyjs){
			startActivity(new Intent(this, qqyyjs.class));
		} else if (id == R.id.nav_sjhgsd){
			startActivity(new Intent(this, sjhgsd.class));
		} else if (id == R.id.nav_wyymck){
			startActivity(new Intent(this, wyymck.class));
		} else if (id == R.id.nav_sdt){
			startActivity(new Intent(this, sdt.class));
		}

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
